package com.card.server.service.impl;

import com.card.server.config.RedisService;
import com.card.server.domain.*;
import com.card.server.enums.TimeEnum;
import com.card.server.service.IStartService;
import com.card.server.utils.GameUtil;
import com.card.server.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.FluxSink;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/5/28 22:48
 * @desc
 */
@Service
public class StartServiceImpl implements IStartService {
    private static final Logger log = LoggerFactory.getLogger(StartServiceImpl.class);
    @Autowired
    private GameUtil gameUtil;
    @Autowired
    private RedisService redisService;
    @Scheduled(fixedRate = 1000)
    public void checkGame() {
        gameUtil.check();
    }

    @Override
    public String call(Boolean flag, Integer userId, String room) {
        log.info("用户-{}", userId + "_" + room);

        String gameKey = "game:" + getRoom(room) + ":";
        GameInfo gameInfo = redisService.getCacheObject(gameKey, GameInfo.class);

        if (gameInfo == null) {
            return "房间不存在";
        }

        // 初始化叫地主记录
        if (gameInfo.getLandlordAuction() == null) {
            gameInfo.setLandlordAuction(new ArrayList<>());
        }

        // 获取所有玩家信息
        List<Player> players = gameInfo.getPlayers();
        boolean found = false;
        int currentAuctionerIndex = -1;

        for (int i = 0; i < players.size(); i++) {
            Player player = players.get(i);
            if (player.getId().equals(userId)) {
                // 构造叫地主记录
                LandlordAuction auction = new LandlordAuction();
                auction.setAuctionFlags(flag);
                auction.setCurrentAuctioner(i);
                auction.setRound(1);

                // 添加到叫地主记录中
                gameInfo.getLandlordAuction().add(auction);

                currentAuctionerIndex = i;
                found = true;
                break;
            }
        }

        if (!found) {
            return "用户不在房间内";
        }

        // 如果用户选择叫地主，则进入下一阶段
        if (Boolean.TRUE.equals(flag)) {
            // 设置游戏状态为 5：表示“叫地主成功”
            gameInfo.setStatus(5);

            // 设置地主玩家编号
            gameInfo.setLandlordPlayer(currentAuctionerIndex);

            // 可选：将底牌合并到地主手中
            List<Card> landlordCards = new ArrayList<>(players.get(currentAuctionerIndex).getCards());
            landlordCards.addAll(gameInfo.getBottomCards());
            players.get(currentAuctionerIndex).setCards(landlordCards); // 更新地主手牌
            gameInfo.setPlayers(players); // 更新玩家列表
            broadcastGameStatus(gameInfo,  getRoom(room), currentAuctionerIndex);
        }

        // 更新 Redis 缓存
        redisService.setCacheObject(gameKey, gameInfo, TimeEnum.ONE_DAY);

        return "叫地主操作成功";
    }

    private String getRoom(String key) {
        return key.substring(key.lastIndexOf(":") + 1);
    }
    private void broadcastGameStatus(GameInfo gameInfo, String room, int landlordIndex) {
        List<Player> players = gameInfo.getPlayers();

        for (int i = 0; i < players.size(); i++) {
            Player player = players.get(i);
            String gameCode = player.getId() + "_" + room;
            log.info("{}", gameCode);
            FluxSink<String> emitter = GameEmitters.playEmitters.get(gameCode);

            if (emitter != null) {
                try {
                    Map<String, Object> message = new HashMap<>();
                    message.put("code", 13); // 进入游戏阶段
                    message.put("landlordIndex", landlordIndex); // 地主编号
                    message.put("index", i);
                    message.put("status", 5); // 状态码

                    // 如果是地主本人，发送底牌信息
                    if (player.getId().equals(gameInfo.getPlayers().get(landlordIndex).getId())) {
                        message.put("bottomCards", gameInfo.getBottomCards()); // 发送底牌数据
                    }

                    emitter.next(JsonUtils.writeValueAsString(message));
                } catch (Exception e) {
                    log.error("SSE 发送失败: {}", e.getMessage());
                }
            }
        }
    }
}
